package androidServlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import sessionMenegment.SessionMgr;
import validate.Validate;

import controller.Controller;
import dataBase.Business;
import dataBase.Order;

@SuppressWarnings("serial")
public class NewOrderAndroid extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		
		System.out.println("new order android");
		PrintWriter out = resp.getWriter();
		
		try{
			int orderID = Integer.parseInt(req.getParameter("orderID"));
			String bizKey = req.getParameter("bizKey");
			String phone = req.getParameter("phone");
			
			//String bizName = req.getParameter("businessName");			
			//System.out.println("!!!!!! "+orderID+" "+bizName);

			System.out.println(bizKey);
			if (Validate.phoneValid(phone))
			{
				String newPhone = phone.replaceAll("-", "");
				String userNameClient = (String) req.getParameter("username");		

				String statusNotification = req.getParameter("statusNotification");
				String messageNotification = req.getParameter("messageNotification");

				System.out.println("?"+statusNotification);
				boolean statusNotificationBoolean = false;
				boolean messageNotificationBoolean = false;

				if (statusNotification!=null && statusNotification.equals("on"))
					statusNotificationBoolean = true;

				if (messageNotification!=null && messageNotification.equals("on"))
					messageNotificationBoolean = true;

				//get biz username
				String bizUserName = null;
				long bizIdLong = Long.parseLong(bizKey);
				Business b = Controller.getInstance().keyToBusiness(bizIdLong);
				int result;
				if (b!=null)
				{
					bizUserName = b.getUserName();
					System.out.println("bizUserName: " +bizUserName);
					result = Controller.getInstance().addOrderToClient(userNameClient,bizUserName, orderID,newPhone, statusNotificationBoolean, messageNotificationBoolean);
				}
				else
				{
					result = 5;
				}

				if (result==0)
				{
					out.println("true");
					System.out.println("111");
				}
				else
				{
					if (result==5)
					{
						out.println("businessName");
					}
					else
					{
						out.println("invalid parameters");
					}
					System.out.println("222  "+result);
				}
			
			}
			else
			{
				out.println("invalid phone number");
				System.out.println("333");
			}
			
		}
		catch(NumberFormatException e)
		{
			out.println("order id is not a number");

		}
		
		out.flush();

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {

	}

}
